package com.huarui.returned.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.ewaf.framework.action.BaseAction;
import org.ewaf.framework.model.ListModel;

import com.huarui.part.model.PartPropertySearch;
import com.huarui.receive.service.ReceiveService;
import com.huarui.returned.model.Returned;
import com.huarui.returned.model.ReturnedButtonEnum;

import com.huarui.returned.model.ReturnedModel;
import com.huarui.returned.service.ReturnedService;
import com.huarui.user.model.SessionMessage;
import com.huarui.user.security.UserHolder;
import com.huarui.util.ConstantUtil;
import com.huarui.util.JsonUtil;

public class ReturnedAction extends BaseAction {

	private static final long serialVersionUID = -2910858946497916568L;
	private Logger log = Logger.getLogger(ReturnedAction.class);
	private String queryParam;//查询参数,传递数据参数  
    private ReceiveService receiveService;
    private ReturnedService returnedService;
    private Map<String,Object> map;
	private JSONObject jsonResult =new JSONObject();
	// 分页
	private Integer start;
	private Integer limit;
	private String sort;
	private String dir;	
	@SuppressWarnings("unchecked")
	private ListModel returnedListModel; 	
	
	private String searchJson;
	/**
	 * 显示退库单明细表
	 * 
	 * @return
	 */
	public String toReturnedItemExt() {
		
		jsonResult = returnedService.generateButtonsByStatus(ReturnedButtonEnum.STATUS_OF_TOCREATE.getType(),null,UserHolder.getCurrentSessionMessage().getUserId());		
		return "toReturnedItems";
	}
	
	public String getInitialButtons(){
		SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
		jsonResult = returnedService.generateButtonsByStatus(Returned.STATUS_TO_CREATE,sessionMessage.getUserId(),sessionMessage.getUserId());		
	    return SUCCESS;
	}
   /**
    * 查询入库单，库存表，选择待退货明细
    */
	@SuppressWarnings("unchecked")
	public String searchReturndItems(){
		JSONObject queryObj = JSONObject.fromObject(queryParam);		
		map = (Map) JSONObject.toBean(queryObj, Map.class);				
		List<Map> result = receiveService.getReceiveItemByConditonsWithInventory(map, UserHolder.getCurrentSessionMessage());			
	    JSONArray ja = JSONArray.fromObject(result);
	    jsonResult.put(ConstantUtil.ROOT, ja);
	    return SUCCESS;
	}
	
	/**
	 * 退货单各状态下的操作
	 * @return {'success':true,'returned':{xxxxx},'returnedItems':[{xxxx},{xxxx}....],'msg':{'confirm'/'alert':xxxxx},'buttons':{'isOwner':true/false,'buttons':{xxxx}}}
	 * or {"success":false,"msg":"xxxxx"}
	 */
	
	/**
	 * 退库单保存草稿
	 * @return
	 */
	public String  backupDraft(){
		try {			
			jsonResult = returnedService.backupDraft(queryParam);
			jsonResult.put(ConstantUtil.SUCCESS, true);
			jsonResult.put(ConstantUtil.MSG, ConstantUtil.SAVE_CREATE_SUCCESS);
		} catch (Exception e) {
			log.error("保存退库单草稿失败.....", e);
			jsonResult.put(ConstantUtil.SUCCESS, false);
			jsonResult.put(ConstantUtil.MSG,"保存退库单草稿失败.....");			
		}
		return SUCCESS;
	}
	/**
	 * 退库单提交仓库操作
	 * @return
	 */
	public String backupSubmit(){
		try {			
			jsonResult = returnedService.backupSubmit(queryParam);
			jsonResult.put(ConstantUtil.SUCCESS, true);
			jsonResult.put(ConstantUtil.MSG, ConstantUtil.RETURNED_SUBMIT_SUCCESS);
		} catch (Exception e) {
			log.error("退库单提交仓库失败.....", e);
			jsonResult.put(ConstantUtil.SUCCESS, false);
			jsonResult.put(ConstantUtil.MSG,"退库单提交仓库失败.....");			
		}
		return SUCCESS;
	}
	/**
	 * 退库单直接退库
	 * @return
	 */
	public String deposit(){
		try {			
			jsonResult = returnedService.backupReturned(queryParam);
			jsonResult.put(ConstantUtil.SUCCESS, true);
			jsonResult.put(ConstantUtil.MSG,ConstantUtil.RETURNED_DEPOSIT_SUCCESS);
		} catch (Exception e) {
			log.error("退库单退库失败...", e);
			jsonResult.put(ConstantUtil.SUCCESS, false);
			jsonResult.put(ConstantUtil.MSG,"退库单退库失败...");			
		}
		return SUCCESS;
		
	}
	/**
	 * 接手单据
	 * @return
	 */
	public String acceptReturned(){
		SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
		try {
			jsonResult = returnedService.updateReturnedCurrentorId(Integer.valueOf(queryParam),sessionMessage.getUserId());
		} catch (Exception e) {			
			log.debug("接手单据失败......", e);
			jsonResult.put(ConstantUtil.SUCCESS, false);
			jsonResult.put(ConstantUtil.MSG, "接手单据失败......");			
		}
		return SUCCESS;
	}
	/**
	 * 释放单据后产生新的按钮
	 * {"isOwner":xxxxx,"buttons":[{xxxx},{xxxx}...],'success':true}
	 * {'success':false}
	 */
	public String releaseReturned(){				
		try {
			jsonResult = returnedService.updateReturnedCurrentorId(Integer.valueOf(queryParam),null);
		} catch (Exception e) {			
			log.debug("释放单据失败......", e);
			jsonResult.put(ConstantUtil.SUCCESS, false);
			jsonResult.put(ConstantUtil.MSG, "释放单据失败......");			
		}
		return SUCCESS;
		
	}
	/**
	 * 退货单内容浏览
	 */
	@SuppressWarnings("unchecked")
	public String fillReturnedBrowser(){
		Map queryMap = new HashMap();
		if (queryParam != null) {
			JSONObject queryObject = JSONObject.fromObject(queryParam);
			queryMap = (Map) JSONObject.toBean(queryObject, Map.class);
		}
		returnedListModel =ListModelParamUtil();
		ListModel<List<ReturnedModel>> returnedListModels = returnedService.getReturnedListModelByConditions(queryMap,returnedListModel);	    
	    jsonResult.put(ConstantUtil.TOTALPROPERTY, returnedListModels.getTotal());
	    jsonResult.put(ConstantUtil.ROOT,  JSONArray.fromObject(returnedListModels.getResult()));
	    return SUCCESS;
	    
	}
	/**
	 * 退货单明细浏览
	 */
	@SuppressWarnings("unchecked")
	public String fillReturnedItemBrowser(){		
		Map queryMap = new HashMap();
		if (queryParam != null) {
			JSONObject queryObject = JSONObject.fromObject(queryParam);
			queryMap = (Map) JSONObject.toBean(queryObject, Map.class);
		}
		if(searchJson!=null){
			PartPropertySearch partPropertySearch=JsonUtil.getBean(searchJson, PartPropertySearch.class);
			queryMap.put("searchJson", partPropertySearch);
		}
		returnedListModel =ListModelParamUtil();
		ListModel<Map> returnedItemList = returnedService.getRerurnedItemByConditions(queryMap,returnedListModel);	    
	    jsonResult.put(ConstantUtil.TOTALPROPERTY, returnedItemList.getTotal());
	    jsonResult.put(ConstantUtil.ROOT,  JSONArray.fromObject(returnedItemList.getResult()));
	    return SUCCESS;
	}
	
	@SuppressWarnings("unchecked")
	private ListModel ListModelParamUtil() {
		returnedListModel = new ListModel();
		returnedListModel.setPage(start ==null && limit == null ? 1: start / limit + 1);
		returnedListModel.setPageSize(limit == null ? ConstantUtil.PAGESIZE : limit);
		returnedListModel.setOrderBy(sort);
		if (dir != null){
			returnedListModel.setDesc(dir.equals(ConstantUtil.DESC) ? true : false);
		}else{
			returnedListModel.setDesc(true);
		}	
		return returnedListModel;
	}
	/**
	 * 根据Id删除退库单草稿
	 * @return {"success":false/true,"msg":"xxxxx"}
	 */
	public String deleteDraft(){		
		try {
			jsonResult = returnedService.deleteReturnedByIdAndBuyerId(Integer.valueOf(queryParam));			
		} catch (Exception e) {			
			log.debug(e.getMessage(), e);
			jsonResult.put(ConstantUtil.SUCCESS, false);	
			jsonResult.put(ConstantUtil.MSG, ConstantUtil.MSG_DELETE_DRAFT_FAILURE);
		}		
		return SUCCESS;
	}
	/**
	 * 返回退库单编辑页面
	 * @return
	 */
	public String toReturnedItemEdit(){		
		try {
			jsonResult = returnedService.generateReturnedAndItemById(Integer.valueOf(queryParam));
			jsonResult.put(ConstantUtil.SUCCESS, true);
			jsonResult.put(ConstantUtil.MSG, "");
		} catch (Exception e) {			
			log.debug(e.getMessage());
			jsonResult.put(ConstantUtil.SUCCESS, false);
			jsonResult.put(ConstantUtil.MSG, ConstantUtil.MSG_GET_DETAIL_FAILURE);		
		}
			return SUCCESS;
	}
	/**
	 * 待仓库确认状态退回草稿状态
	 * {'success':true,'returned':{xxxxx},'returnedItems':[{xxxx},{xxxx}....],'msg':'','buttons':{'isOwner':true/false,'buttons':{xxxx}}}
	 * {'success':false,'msg':'发生异常'};
	 */
	public String backToDraft(){		
		try {
			jsonResult = returnedService.updateReturnedStatusById(Integer.valueOf(queryParam));
		} catch (Exception e) {			
			log.debug(e.getMessage());
			jsonResult.put(ConstantUtil.SUCCESS, false);
			jsonResult.put(ConstantUtil.MSG,ConstantUtil.MSG_BACKTO_DRAFT_FAILURE);			
		}
		return SUCCESS;
	}

	public void setQueryParam(String queryParam) {
		this.queryParam = queryParam;
	}

	public void setReceiveService(ReceiveService receiveService) {
		this.receiveService = receiveService;
	}

	public void setReturnedService(ReturnedService returnedService) {
		this.returnedService = returnedService;
	}

	public void setMap(Map<String, Object> map) {
		this.map = map;
	}

	public void setJsonResult(JSONObject jsonResult) {
		this.jsonResult = jsonResult;
	}

	public void setStart(Integer start) {
		this.start = start;
	}

	public void setLimit(Integer limit) {
		this.limit = limit;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public void setDir(String dir) {
		this.dir = dir;
	}

	@SuppressWarnings("unchecked")
	public void setReturnedListModel(ListModel returnedListModel) {
		this.returnedListModel = returnedListModel;
	}

	public JSONObject getJsonResult() {
		return jsonResult;
	}

	public void setSearchJson(String searchJson) {
		this.searchJson = searchJson;
	}
	

	
	
	
  
	
}
